package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("save dish : {}", dishDTO);
        dishService.saveDishAndFlavor(dishDTO);
        //清理缓存
        cleanCache("dish_"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    public Result<PageResult>page(DishPageQueryDTO dishPageQueryDTO){
        log.info("page dish : {}", dishPageQueryDTO);
        PageResult result=dishService.pageQuery(dishPageQueryDTO);
        return Result.success(result);
    }


    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        log.info("delete dish : {}", ids);
        dishService.deleteBatch(ids);
        //将所有dish_缓存清理
        cleanCache("dish_*");

        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("get dish by id : {}", id);
        DishVO dishVO=dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("update dish : {}", dishDTO);
        dishService.updateWithFlavor(dishDTO);
        //将所有dish_缓存清理
        cleanCache("dish_*");
        return Result.success();
    }

    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id){
        dishService.startOrStop(status,id);
        //将所有dish_缓存清理
        cleanCache("dish_*");
        return Result.success();
    }

    //清理缓存
    private void cleanCache(String keyPatten){
        Set keys = redisTemplate.keys(keyPatten);
        redisTemplate.delete(keys);
    }


    @GetMapping("/list")
    public Result<List<Dish>> listBycategoryId(Long categoryId) {
        List<Dish> list = dishService.listBycategoryId(categoryId);
        return Result.success(list);
    }

}
